<template>
  <view class="detail-page">
    <view class="card">
      <image class="avatar" :src="info.img || defaultAvatar" mode="aspectFill" />
      <view class="card-body">
        <view class="name-row">
          <text class="name">{{ info.name }}</text>
          <view class="stars">
            <text class="score">{{ Number(info.star||0).toFixed(1) }}★</text>
          </view>
        </view>
        <view class="tags">
          <text class="tag">已认证</text>
          <text class="tag light">入驻：{{ formatDate(info.createTime) || '—' }}</text>
        </view>
        <view class="price-row">
          <text class="price">¥{{ Number(info.price||0).toFixed(2) }}/小时</text>
          <button class="btn small" @tap="book">预约</button>
        </view>
      </view>
    </view>

    <view class="panel">
      <text class="panel-title">简介</text>
      <text class="bio">{{ info.bio || '暂无简介' }}</text>
    </view>

    <view class="tabs">
      <text :class="['tab', {active: rateFilter===0}]" @tap="changeFilter(0)">全部评价</text>
      <text :class="['tab', {active: rateFilter===5}]" @tap="changeFilter(5)">五星好评</text>
      <text :class="['tab', {active: rateFilter===4}]" @tap="changeFilter(4)">四星好评</text>
      <text :class="['tab', {active: rateFilter===3}]" @tap="changeFilter(3)">三星及以下</text>
    </view>

    <view class="panel">
      <text class="panel-title">用户评价</text>
      <view v-if="fbLoading" class="loading">加载评论中...</view>
      <view v-else-if="fbError" class="error">{{ fbError }}</view>
      <view v-else>
        <view v-if="!filteredFeedbacks.length" class="loading">暂无评论</view>
        <view v-else>
          <view class="comment" v-for="(c, i) in filteredFeedbacks" :key="c.id">
            <image class="comment-avatar" :src="defaultAvatar" mode="aspectFill" />
            <view class="comment-main">
              <view class="comment-head">
                <text class="comment-user">用户{{ c.userId }}</text>
                <text class="score">{{ Number(c.rating||0).toFixed(1) }}★</text>
              </view>
              <text class="comment-text">{{ c.comment || '' }}</text>
              <view class="comment-foot">
                <text class="comment-time">{{ formatDateTime(c.createTime) }}</text>
                <view class="thumbs">
                  <text class="thumb">👍</text>
                  <text class="thumb">💬</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="footer">
      <button class="btn" @tap="book">预约</button>
    </view>
  </view>
  
</template>

<script>
import { getCoachDetail } from '@/api/coach'
import { listFeedbackByCompanion } from '@/api/feedback'
export default {
  data(){
    return {
      id: '',
      info: {},
      loading: false,
      error: '',
      feedbacks: [],
      fbLoading: false,
      fbError: '',
      rateFilter: 0,
      defaultAvatar: '/static/project/2025-10-14_110352_756.png'
    }
  },
  computed: {
    filteredFeedbacks(){
      if (!Array.isArray(this.feedbacks)) return []
      if (!this.rateFilter) return this.feedbacks
      if (this.rateFilter === 3) return this.feedbacks.filter(i => Number(i.rating||0) <= 3)
      return this.feedbacks.filter(i => Math.round(Number(i.rating||0)) === this.rateFilter)
    }
  },
  onLoad(query){
    this.id = query && (query.id || query.coachId)
    this.fetchDetail()
    this.fetchFeedbacks()
  },
  methods: {
    async fetchDetail(){
      if (!this.id) return
      this.loading = true
      this.error = ''
      try{
        const res = await getCoachDetail(this.id)
        const data = res.data || res
        this.info = this.mapInfo(data)
      }catch(e){
        this.error = (e && e.msg) || '加载失败'
      }finally{
        this.loading = false
      }
    },
    async fetchFeedbacks(){
      if (!this.id) return
      this.fbLoading = true
      this.fbError = ''
      try{
        const res = await listFeedbackByCompanion(this.id)
        const list = (Array.isArray(res.data) ? res.data : (res.rows || res.list || []))
        this.feedbacks = (list || []).map(this.mapFeedback)
      }catch(e){
        this.fbError = (e && e.msg) || '加载评论失败'
      }finally{
        this.fbLoading = false
      }
    },
    mapInfo(raw){
      return {
        id: raw.id || raw.user_id || raw.userId,
        name: raw.name || '未命名',
        star: Number(raw.score || 0),
        price: Number(raw.price || 0),
        bio: raw.bio || '',
        createTime: raw.create_time || raw.createTime || '',
        img: raw.img || raw.avatar || this.defaultAvatar
      }
    },
    mapFeedback(raw){
      return {
        id: raw.id,
        orderId: raw.order_id || raw.orderId,
        userId: raw.user_id || raw.userId,
        companionId: raw.companion_id || raw.companionId,
        rating: Number(raw.rating || 0),
        comment: raw.comment || '',
        createTime: raw.create_time || raw.createTime
      }
    },
    formatDate(val){
      if (!val) return ''
      const d = typeof val === 'number' ? new Date(val) : new Date(String(val).replace(/-/g,'/'))
      if (isNaN(d.getTime())) return String(val)
      const pad = n => (n<10?('0'+n):n)
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`
    },
    formatDateTime(val){
      if (!val) return ''
      const d = typeof val === 'number' ? new Date(val) : new Date(String(val).replace(/-/g,'/'))
      if (isNaN(d.getTime())) return String(val)
      const pad = n => (n<10?('0'+n):n)
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
    },
    book(){
      if (!this.id) {
        this.$modal && this.$modal.showToast('缺少ID，无法预约')
        return
      }
      const price = Number(this.info && this.info.price || 0)
      uni.navigateTo({ url: `/pages/order/create?id=${this.id}&price=${price}` })
    },
    changeFilter(val){
      this.rateFilter = val
    }
  }
}
</script>

<style scoped>
.detail-page { padding: 16rpx 16rpx 120rpx 16rpx; background:#f7fafc; }
.card { display:flex; background:#fff; border-radius: 16rpx; padding: 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.06); }
.avatar { width: 160rpx; height: 160rpx; border-radius: 12rpx; background:#f3f4f6; }
.card-body { flex:1; margin-left: 16rpx; }
.name-row { display:flex; align-items:center; justify-content: space-between; }
.name { font-size: 34rpx; font-weight: 700; }
.stars { display:flex; align-items:center; color:#f59e0b; }
.stars.small { font-size: 22rpx; }
.star { margin-left: 4rpx; }
.score { margin-left: 6rpx; color:#f59e0b; font-weight: 600; }
.tags { margin-top: 6rpx; }
.tag { display:inline-block; padding: 4rpx 10rpx; border-radius: 999rpx; background:#ecfeff; color:#0ea5a5; font-size: 20rpx; margin-right: 8rpx; }
.tag.light { background:#f3f4f6; color:#6b7280; }
.price-row { display:flex; align-items:center; justify-content: space-between; margin-top: 10rpx; }
.price { color:#0ea5a5; font-weight: 700; }
.btn { background:#0ea5a5; color:#fff; border:none; }
.btn.small { padding: 0 20rpx; }
.panel { margin-top: 16rpx; background:#fff; border-radius: 16rpx; padding: 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.06); }
.panel-title { display:block; font-size: 28rpx; font-weight: 700; margin-bottom: 8rpx; }
.bio { color:#4b5563; line-height: 1.6; }
.tabs { display:flex; gap: 12rpx; margin: 16rpx 0; }
.tab { padding: 8rpx 16rpx; border-radius: 999rpx; background:#f3f4f6; color:#6b7280; }
.tab.active { background:#ecfeff; color:#0ea5a5; }
.comment { display:flex; gap: 12rpx; background:#fff; border-radius: 16rpx; padding: 12rpx; box-shadow: 0 6rpx 20rpx rgba(0,0,0,.04); margin-bottom: 12rpx; }
.comment-avatar { width: 64rpx; height: 64rpx; border-radius: 50%; background:#f3f4f6; }
.comment-main { flex:1; }
.comment-head { display:flex; align-items:center; justify-content: space-between; }
.comment-user { font-weight: 600; }
.comment-text { display:block; margin: 6rpx 0; color:#374151; }
.comment-foot { display:flex; align-items:center; justify-content: space-between; color:#9ca3af; font-size: 22rpx; }
.thumbs { display:flex; gap: 12rpx; color:#6b7280; }
.footer { position: fixed; left:0; right:0; bottom:0; padding: 12rpx 16rpx; background: #fff; box-shadow: 0 -6rpx 20rpx rgba(0,0,0,.06); }
.loading { padding: 12rpx; color:#6b7280; }
.error { padding: 12rpx; color:#ef4444; }
</style>


